<template>
  <el-row>
    <el-col :span="24">
      <el-card>
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item>
            <el-button style="margin-bottom: 10px;" type="success" @click="addDialogShow=true">添加</el-button>
          </el-form-item>
          <el-form-item style="float: right;">
            <el-input v-model="condition.name" placeholder="请输入要搜索的名称" @input="selectByPage(1);"/>
          </el-form-item>
          <el-form-item style="float: right;">
            <el-select
                v-model="condition.status"
                :value-on-clear="null"
                clearable
                placeholder="强选择是否上架"
                style="width: 150px"
                @change="selectByPage(1)">
              <el-option label="上架" value="1"/>
              <el-option label="下架" value="0"/>
            </el-select>
          </el-form-item>
          <el-form-item style="float: right" width="200px">
            <el-cascader
                v-model="condition.categoryId"
                :options="allParent"
                :props="props"
                :value-on-clear="null"
                clearable
                placeholder="请选择分类"
                @change="selectByPage(1)"
            />

          </el-form-item>
        </el-form>
        <el-table :data="pageInfo.list" border style="width: 100%">
          <el-table-column label="ID" prop="id" width="50px"/>
          <el-table-column label="名称" prop="name"/>
          <el-table-column label="描述" prop="dscp"/>
          <el-table-column label="售价" prop="price"/>
          <el-table-column label="标价" prop="markPrice"/>
          <el-table-column label="进价" prop="purchasePrice"/>
          <el-table-column label="颜色" prop="color"/>
          <el-table-column label="版本" prop="version"/>
          <el-table-column label="数量" prop="count"/>
          <el-table-column label="是否推荐">
            <template #default="scope">
              <el-tag v-if="scope.row.recom == 1" type="primary">推荐</el-tag>
              <el-tag v-if="scope.row.recom == 0" type="warning">不推荐</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="分类">
            <template #default="scope">
              <el-text class="mx-1" type="primary">{{ scope.row.category.name }}</el-text>
            </template>
          </el-table-column>
          <el-table-column label="评分" prop="score" width="50px"/>
          <el-table-column label="是否上架">
            <template #default="scope">
              <el-tag v-if="scope.row.status == 1" type="primary">上架</el-tag>
              <el-tag v-if="scope.row.status == 0" type="primary">下架</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="图片">
            <template #default="scope">
              <el-popover :width="300" placement="right" trigger="hover">
                <template #reference>
                  <el-image
                      v-if="scope.row.picList && scope.row.picList.length > 0 && scope.row.picList[0].url"
                      :src="SERVER_ADDR +'/goods/pic/' +scope.row.picList[0].url" style="width: 20px;height: 20px"/>
                </template>
                <el-image v-for="(pic, index) in scope.row.picList" :key="index" :src="SERVER_ADDR +'/category/pic/' + pic.url"
                          style="width: 20px;height: 20px"/>
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button size="small" type="success" @click="showDetailDialog(scope.row.id)">详情</el-button>
              <el-button size="small" type="primary" @click="selectById(scope.row.id)">修改</el-button>
              <el-popconfirm cancel-button-text="取消" confirm-button-text="确认" title="你确定要删除该车辆吗?"
                             width="200px"
                             @confirm="deleteGoods(scope.row.id)">
                <template #reference>
                  <el-button size="small" type="danger">删除</el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <el-row class="row-bg" justify="center" style="margin-top: 20px;">
          <el-pagination v-model:current-page="pageInfo.pageNum" :page-count="pageInfo.pages"
                         background
                         layout="prev, pager, next"
                         @update:current-page="selectByPage"/>
        </el-row>
      </el-card>
    </el-col>
  </el-row>


  <!-- 添加模态框开始 -->
  <el-dialog v-model="addDialogShow" title="添加商品" width="500px">
    <el-form>
      <el-form-item label="分类" label-width="20%">
        <el-cascader
            v-model="goodsAdd.categoryId"
            :options="allParent"
            :props="props"
            :value-on-clear="null"
            clearable
            placeholder="请选择分类"
        />
      </el-form-item>
      <el-form-item label="名称" label-width="20%">
        <el-input v-model="goodsAdd.name" autocomplete="off" placeholder="请输入名称"/>
      </el-form-item>
      <el-form-item label="描述" label-width="20%">
        <el-input v-model="goodsAdd.dscp" autocomplete="off" placeholder="请输入描述"/>
      </el-form-item>
      <el-form-item label="售价" label-width="20%">
        <el-input v-model="goodsAdd.price" autocomplete="off" placeholder="请输入售价"/>
      </el-form-item>
      <el-form-item label="标价" label-width="20%">
        <el-input v-model="goodsAdd.markPrice" autocomplete="off" placeholder="请输入标价"/>
      </el-form-item>
      <el-form-item label="进价" label-width="20%">
        <el-input v-model="goodsAdd.purchasePrice" autocomplete="off" placeholder="请输入进价"/>
      </el-form-item>
      <el-form-item label="颜色" label-width="20%">
        <el-input v-model="goodsAdd.color" autocomplete="off" placeholder="请输入颜色"/>
      </el-form-item>
      <el-form-item label="版本" label-width="20%">
        <el-input v-model="goodsAdd.version" autocomplete="off" placeholder="请输入版本"/>
      </el-form-item>
      <el-form-item label="数量" label-width="20%">
        <el-input v-model="goodsAdd.count" autocomplete="off" placeholder="请输入数量"/>
      </el-form-item>

      <el-form-item label="是否推荐" label-width="20%">
        <el-radio-group v-model="goodsAdd.recom">
          <el-radio :value="0" label="不推荐" size="large"/>
          <el-radio :value="1" label="推荐" size="large"/>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否上架" label-width="20%">
        <el-radio-group v-model="goodsAdd.status">
          <el-radio :value="0" label="上架" size="large"/>
          <el-radio :value="1" label="下架" size="large"/>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="图片" label-width="20%">
        <el-upload v-model:file-list="goodsAdd.picList" :action=" SERVER_ADDR + '/category/upload'"
                   :before-upload="beforepicUpload" :on-success="picUploadSuccess"
                   class="avatar-uploader" :headers="headers"
                   list-type="picture-card" name="pic">
          <el-icon>
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="addDialogShow = false">取消</el-button>
        <el-button type="primary" @click="insert"> 确认</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 添加模态框结束 -->
  <!-- 修改模态框开始 -->
  <el-dialog v-model="updateDialogShow" title="添加商品" width="500px">
    <el-form>
      <el-form-item label="分类" label-width="20%">
        <el-cascader
            v-model="goodsUpdate.categoryId"
            :options="allParent"
            :props="props"
            :value-on-clear="null"
            clearable
            placeholder="请选择分类"
        />
      </el-form-item>
      <el-form-item label="名称" label-width="20%">
        <el-input v-model="goodsUpdate.name" autocomplete="off" placeholder="请输入名称"/>
      </el-form-item>
      <el-form-item label="描述" label-width="20%">
        <el-input v-model="goodsUpdate.dscp" autocomplete="off" placeholder="请输入描述"/>
      </el-form-item>
      <el-form-item label="售价" label-width="20%">
        <el-input v-model="goodsUpdate.price" autocomplete="off" placeholder="请输入售价"/>
      </el-form-item>
      <el-form-item label="标价" label-width="20%">
        <el-input v-model="goodsUpdate.markPrice" autocomplete="off" placeholder="请输入标价"/>
      </el-form-item>
      <el-form-item label="进价" label-width="20%">
        <el-input v-model="goodsUpdate.purchasePrice" autocomplete="off" placeholder="请输入进价"/>
      </el-form-item>
      <el-form-item label="颜色" label-width="20%">
        <el-input v-model="goodsUpdate.color" autocomplete="off" placeholder="请输入颜色"/>
      </el-form-item>
      <el-form-item label="版本" label-width="20%">
        <el-input v-model="goodsUpdate.version" autocomplete="off" placeholder="请输入版本"/>
      </el-form-item>
      <el-form-item label="数量" label-width="20%">
        <el-input v-model="goodsUpdate.count" autocomplete="off" placeholder="请输入数量"/>
      </el-form-item>

      <el-form-item label="是否推荐" label-width="20%">
        <el-radio-group v-model="goodsUpdate.recom">
          <el-radio :value="0" label="不推荐" size="large"/>
          <el-radio :value="1" label="推荐" size="large"/>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否上架" label-width="20%">
        <el-radio-group v-model="goodsUpdate.status">
          <el-radio :value="1" label="上架" size="large"/>
          <el-radio :value="0" label="下架" size="large"/>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="图片" label-width="20%">
        <el-upload v-model:file-list="goodsUpdate.picList" :action=" SERVER_ADDR + '/category/upload'"
                   :before-upload="beforepicUpload" :on-success="picUploadSuccess" :headers="headers"
                   class="avatar-uploader"
                   list-type="picture-card" name="pic">
          <el-icon>
            <Plus/>
          </el-icon>
        </el-upload>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="updateDialogShow = false">取消</el-button>
        <el-button type="primary" @click="update"> 确认</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 修改模态框结束 -->
  <!--商品详情模态框开始 -->
  <el-dialog v-model="detailDialogShow" title="添加商品" width="500px">
    <div v-if="detailDialogShow" style="border: 1px solid #ccc">
      <Toolbar
          :defaultConfig="toolbarConfig"
          :editor="editorRef"
          :mode="mode"
          style="border-bottom: 1px solid #ccc"
      />
      <Editor
          v-model="goodsUpdate.detail"
          :defaultConfig="editorConfig"
          :mode="mode"
          style="height: 500px; overflow-y: hidden;"
          @onCreated="handleCreated"
      />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="detailDialogShow = false">取消</el-button>
        <el-button type="primary" @click="updateDetail"> 确认</el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 商品详情模态框结束 -->

</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import GoodsApi from "@/api/goodsApi.js";
import {onBeforeUnmount, ref, shallowRef, onMounted, computed} from 'vue'
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import {ElMessage} from "element-plus";
import categoryApi from "@/api/categoryApi.js";
import goodsApi from "@/api/goodsApi.js";
import {useTokenStore} from "@/stores/token.js";

const  tokenStore=useTokenStore();
const headers =computed(()=>{
  const token = tokenStore.tokenStr;
  return{
    token
  }
});
const SERVER_ADDR = ref(import.meta.env.VITE_SERVER_ADDR);
//文本编辑器
const editorRef = shallowRef()
const mode = ref('default');
const toolbarConfig = {}
const editorConfig = {
  placeholder: '请输入内容...',
  MENU_CONF: {
    uploadImage: {
      server: `${SERVER_ADDR.value}/goods/upload`,
      fieldName: 'pic',
      headers:{
          token:tokenStore.token
      },
      customInsert(resp, insertFn) {
        let url = `${SERVER_ADDR.value}/goods/pic/${resp.data}`;
        insertFn(url);
      }
    }
  }
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

//显示商品详情的对话框
function showDetailDialog(id) {
  goodsApi.selectById(id)
      .then(resp=>{
        goodsUpdate.value.id=resp.data.id;
        goodsUpdate.value.detail=resp.data.detail;
        goodsUpdate.value.picList=resp.data.picList;
          })
  detailDialogShow.value = true;
}


const condition = ref({
  name: null,
  categoryId: null,//子分类的id
  states: null
});
//父分类
const allParent = ref([]);
//级联选择器配置
const props = {
  label: "name",
  value: "id",
  children: "childList",
  emitPath: false
}


//分页信息
const pageInfo = ref({
  pages: 0,
  pageSize: 0,
  pageNum: 0
});
//被添加商品的信息
const goodsAdd = ref({
  name: '',
  dscp: '',
  price: null,
  markPrice: null,
  purchasePrice: null,
  color: null,
  version: null,
  count: null,
  categoryid: null,
  status: null,
  picList: []
});
const goodsUpdate = ref({
  id: 0,
  name: '',
  dscp: '',
  detail: '',
  price: null,
  markPrice: null,
  purchasePrice: null,
  color: null,
  version: null,
  count: null,
  categoryid: null,
  status: null,
  picList: []
});
// //是否显示添加对话框
const addDialogShow = ref(false);
const updateDialogShow = ref(false);
const detailDialogShow = ref(false);

//根据id查询
function selectById(id) {
  goodsApi.selectById(id)
      .then(resp => {
        goodsUpdate.value = resp.data;
        for (let i = 0; i < goodsUpdate.value.picList.length; i++) {
          goodsUpdate.value.picList[i].realName = goodsUpdate.value.picList[i].url;
          goodsUpdate.value.picList[i].url = `${SERVER_ADDR.value}/goods/pic/${goodsUpdate.value.picList[i].url}`;
        }
        updateDialogShow.value = true;
      })
}

function updateDetail() {
  goodsApi.update(goodsUpdate.value)
      .then(resp => {
        if (resp.code == 10000) {
          ElMessage.success(resp.msg);
          detailDialogShow.value = false;
          //
          goodsUpdate.value = {
            id: 0,
            name: '',
            dscp: '',
            detail: '',
            price: null,
            markPrice: null,
            purchasePrice: null,
            color: null,
            version: null,
            count: null,
            categoryid: null,
            status: null,
            picList: []
          };
          //查询第一页
          selectByPage(pageInfo.value.pageNum);
        } else {
          ElMessage.error(resp.msg);
        }
      })
}

//修改
function update() {
  for (let i = 0; i < goodsUpdate.value.picList.length; i++) {
    goodsUpdate.value.picList[i].url = goodsUpdate.value.picList[i].realName;
  }
  goodsApi.update(goodsUpdate.value)
      .then(resp => {
        if (resp.code == 10000) {
          ElMessage.success(resp.msg);
          updateDialogShow.value = false;
          goodsUpdate.value = {
            id: 0,
            name: '',
            dscp: '',
            detail: '',
            price: null,
            markPrice: null,
            purchasePrice: null,
            color: null,
            version: null,
            count: null,
            categoryid: null,
            status: null,
            picList: []
          };
          //查询第一页
          selectByPage(pageInfo.value.pageNum);
        } else {
          ElMessage.error(resp.msg);
        }
      })
}

//上传图片之前的回调
function beforepicUpload(rawFile) {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('图片仅支持jpg格式');
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("图片不能超过2M");
    return false
  }
  return true
}

//添加图片上传成功的回调
function picUploadSuccess(resp, uploadFile) {
  if (resp.code == 10000) {
    ElMessage.success(resp.msg);
    uploadFile.url = `${SERVER_ADDR.value}/goods/pic/${resp.data}`;
    uploadFile.realName = resp.data;
  } else {
    ElMessage.error(resp.msg);
  }
}

function insert() {
  for (let i = 0; i < goodsAdd.value.picList.length; i++) {
    goodsAdd.value.picList[i].url = goodsAdd.value.picList[i].realName;
  }
  goodsApi.inster(goodsAdd.value)
      .then(resp => {
        if (resp.code == 10000) {
          ElMessage.success(resp.msg);
          addDialogShow.value = false;
          goodsAdd.value = {
            name: '',
            dscp: '',
            price: null,
            markPrice: null,
            purchasePrice: null,
            color: null,
            version: null,
            count: null,
            categoryid: null,
            status: null,
            picList: []
          };
          //查询第一页
          selectByPage(pageInfo.value.pageNum);
        } else {
          ElMessage.error(resp.msg);
        }
      });
}

//删除
function deleteGoods(id) {
  GoodsApi.delete(id)
      .then(resp => {
        if (resp.code == 10000) {
          ElMessage.success(resp.msg);
          //查询第一页
          selectByPage(pageInfo.value.pageNum);
        } else {
          ElMessage.error(resp.msg);
        }
      })
}

//分类
function selectAllParent() {
  categoryApi.selectAllParent()
      .then(resp => {
        allParent.value = resp.data;
      })
}

//分页查询
function selectByPage(pageNum) {
  GoodsApi.selectByPage(condition.value, pageNum, 10)
      .then(resp => {
        pageInfo.value = resp.data;
      })
}

selectAllParent();
selectByPage(1);
</script>
<style scoped>
</style>